package what.the.fun.controller;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import what.the.fun.domain.Answer;
import what.the.fun.domain.AnswerStatistic;
import what.the.fun.domain.Campaign;
import what.the.fun.domain.QuestAnsList;
import what.the.fun.domain.Question;
import what.the.fun.domain.Survey;
import what.the.fun.services.AnswerService;
import what.the.fun.services.CampaignService;
import what.the.fun.services.QuestionService;
import what.the.fun.services.SurveyService;

@Controller
public class SurveyController {
	
	@Autowired  
	CampaignService campaignService;
	@Autowired  
	SurveyService surveyService;
	@Autowired
	QuestionService questionService;
	@Autowired
	AnswerService answerService;
	
	ModelAndView loginMaV = new ModelAndView("/user/login");
	ModelAndView errorMaV = new ModelAndView("/other/error");
	
	@RequestMapping("/survey-list-all")
	public ModelAndView surveyList() {
		List<Survey> surveyList = surveyService.getDataList();
		ModelMap model = new ModelMap();
		model.put("surveyList", surveyList);
		return new ModelAndView("survey/survey-list-all", "model", model);
	}
	
	@RequestMapping("/survey-create")
	public ModelAndView createSurvey(HttpSession session, @ModelAttribute Survey survey, String campId) {
		if (session.getAttribute("userId") != null) {	
			Campaign campaign = campaignService.getData(campId);
			if (session.getAttribute("userId").toString().equals(campaign.getUserId())) {
				Map<String, String> map = new HashMap<String, String>();
				map.put("campId", campId);
				return new ModelAndView("survey/survey-create", "map", map);
			}
			else {
				return errorMaV;
			}
		} else {
			 return loginMaV;
		 }
	}
	
	@RequestMapping("/survey-insert")
	public String insertSurvey(HttpSession session, @ModelAttribute Survey survey, String campId) {
		if (session.getAttribute("userId") != null) {
			if (survey != null) {
				survey.setCampId(campId);
				surveyService.insertData(survey);
				return "redirect:/camp-detail?campId=" + campId;
			}
			return "redirect:/error";
		}
		 else {
			 return "redirect:/login";
		 }
	}
	
	@RequestMapping("/survey-detail")
	public ModelAndView detailSurvey(HttpSession session, @RequestParam String surveyId) {
		if (session.getAttribute("userId") != null) {
			Survey survey = surveyService.getData(surveyId);
			Campaign campaign = campaignService.getData(survey.getCampId());
			ModelMap model;
			if (session.getAttribute("userId").toString().equals(campaign.getUserId())) {
				 List<Question> questionList = new ArrayList<Question>();
				 questionList = questionService.getQuestionListBySurveyId(surveyId);
				 model = new ModelMap();
				 model.put("questionList", questionList);
				 
				 model.addAttribute("survey", survey);
				 return new ModelAndView("survey/survey-detail", "model", model);
			} else {
				return errorMaV;
			}
				 
		} else {
			 return loginMaV;
		 }
	 }
	
	@RequestMapping("/survey-statistic")
	public ModelAndView statisticSurvey(HttpSession session, @RequestParam String surveyId) {
		if (session.getAttribute("userId") != null) {
			ModelMap model = new ModelMap();
			
			// Get the answerIds and the time they appears
			List<AnswerStatistic> listAnswerStatistic = new ArrayList<AnswerStatistic>();
			listAnswerStatistic = surveyService.getAnswerStatisticListBySurveyId(surveyId);
			
			List<Question> questList = questionService.getQuestionListBySurveyId(surveyId);
			List<Answer> answerList = new ArrayList<Answer>();
			List<QuestAnsList> listQuestAnsList = new ArrayList<QuestAnsList>();
			
			
			// Put answer count into a hashmap with key is answerContent
			// Calculate the total answer
			int answerTotal = 0;
			HashMap<String, Integer> map = new HashMap<String, Integer>();
			Answer answer;
			for(AnswerStatistic a: listAnswerStatistic) {
				answer = answerService.getData(a.getAnswerId());
				answerList.add(answer);
				map.put(answer.getAnswerContent(), a.getCount());
				//answerTotal += a.getCount();
			}
			
			
			HashMap<String, Float> map2 = new HashMap<String, Float>();
			for(AnswerStatistic a: listAnswerStatistic) {
				answer = answerService.getData(a.getAnswerId());
			}
			
			QuestAnsList questAnsList;
			List<Answer> tempList;
			
			for(Question q:questList) {
				questAnsList = new QuestAnsList();
				questAnsList.setQuestion(q);
				tempList = new ArrayList<Answer>();
				
				// Calculate the percent of an answer and put it into a hashmap
				for(Answer a: answerList) {
					if (a.getQuestId().equals(q.getQuestId())) {
						tempList.add(a);
						answerTotal += map.get(a.getAnswerContent());
					}
				}
				questAnsList.setAnswerList(tempList);
				listQuestAnsList.add(questAnsList);
				
				for(Answer a: answerList) {
					if (a.getQuestId().equals(q.getQuestId())) {
						map2.put(a.getAnswerContent(), round(((float)map.get(a.getAnswerContent())/answerTotal) * 100f, 2));
					}
				}
				answerTotal = 0;
			}
			
			
			model.put("listQuestAnsList", listQuestAnsList);
			model.put("map", map);
			model.put("map2", map2);
			
			Survey survey = surveyService.getData(surveyId);
			Campaign campaign = campaignService.getData(survey.getCampId());
			
			model.addAttribute("survey", survey);
			model.addAttribute("campaign", campaign);
			return new ModelAndView("survey/survey-statistic", "model", model);
		} else {
			 return loginMaV;
		}
	}
	

	public static float round(float d, int decimalPlace) {
        BigDecimal bd = new BigDecimal(Float.toString(d));
        bd = bd.setScale(decimalPlace, BigDecimal.ROUND_HALF_UP);
        return bd.floatValue();
    }
}
